package dproxy.server.net.protocol;

import java.net.URI;
import java.util.Date;
import java.util.Map;

import dproxy.server.cache.to.RequestResponse;
import dproxy.server.common.util.UtilConvert;

/**
 * Basic protocol functionality. Utility class to implement 
 * protocols.
 */
public abstract class BaseProtocol implements Protocol {
    
    /** Protocol description (defined on XML file). */
    private String description;

    /** Initialization parameters. */
    private Map <String, String> initParams;
    
    /**
     * @see dproxy.server.net.protocol.Protocol#init()
     */
    public void init() {
        
    }
    
    /**
     * Create a key conatining:
     * protocolName#requestHashCode#requestFirstNCharacters.
     * @param request Byte array request
     * @return basic key
     */
    protected String createSimpleKey(byte[] request) {
        int keyMaxLen = getKeyMaxLen(request);
        String requestFirstNChars = UtilConvert.convertToString(request, keyMaxLen);

        // Assemples the key
        StringBuffer keyBuffer = new StringBuffer();
        keyBuffer.append(getName());
        keyBuffer.append("#");
        keyBuffer.append(requestFirstNChars.hashCode());
        keyBuffer.append("#");
        keyBuffer.append(requestFirstNChars);
        
        return keyBuffer.toString().substring(0, keyMaxLen);
    }

    /**
     * Gets the Key max len (greater value between Database max and request lenght)
     * @param request lenght
     * @return size
     */
	protected int getKeyMaxLen(byte[] request) {
		int keyMaxLen = RequestResponse.KEY_MAX_LENGHT;
        if (keyMaxLen > request.length) {
            keyMaxLen = request.length;
        }
		return keyMaxLen;
	}
    

    /**
     * @see dproxy.server.net.protocol.Protocol#parseRequestAddress(byte[])
     */
	public URI parseRequestAddress(byte[] request) {
		// Not needed for most protocols
		return null;
	}
	
    /**
     * @see dproxy.server.net.protocol.Protocol#timeout(java.util.Date)
     */
    public boolean timeout(Date requestDate) {
        // Default implementation. Requests never expire from cache
        return false;
    }

    /* Getters and setters: */
    /**
     * @see dproxy.server.net.protocol.Protocol#getDescription()
     */
    public String getDescription() {
        return description;
    }

    /**
     * @see dproxy.server.net.protocol.Protocol#setDescription(String)
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * @see dproxy.server.net.protocol.Protocol#getInitParams()
     */
    public Map<String, String> getInitParams() {
        return initParams;
    }

    /**
     * @see dproxy.server.net.protocol.Protocol#setInitParams(Map)
     */
    public void setInitParams(Map<String, String> initParams) {
        this.initParams = initParams;
    }
}
